package com.dao;

import java.sql.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.model.Branch;
import com.model.CFUser;

@Repository("branchDao")
public class BranchDaoImpl implements BranchDao{
	
	@Autowired
	private SessionFactory sessionFactory;
	public Session getSession()
	{
		return sessionFactory.getCurrentSession();
	}
	@Override
	public void add(Branch branch) {
		Session session= sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(branch);
		session.flush();
	}
	@Override
	public Branch findByName(String branchName) {
		Query query=getSession().createQuery("from Branch where branchName ='" + branchName + "'");
		return (Branch) query.uniqueResult();
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Branch> getAll(int page) {
		return getSession().createCriteria(Branch.class) 
				.addOrder(Order.desc("branchId"))
				.setFirstResult((page-1) * 5).setMaxResults(5).setFetchSize(5)
				.list(); 
				
	}

	@SuppressWarnings("rawtypes")
	public List getBranchName()
	{
		String sql="select branchId, branchName from branch";
		SQLQuery query = getSession().createSQLQuery(sql);
        query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
        return query.list();
			
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Branch> getAll() {
		return (List<Branch>) getSession().createCriteria(Branch.class).list();	
	}

	@Override
	public Branch get(Integer id) {
		return (Branch)getSession().get(Branch.class, id);	
	}

	@Override
	public void delete(Integer id) {

		Branch branch= (Branch) getSession().get(Branch.class, id);
			getSession().delete(branch);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Branch> getByDate(Date from, Date to) {
		Criteria criteria = getSession().createCriteria(Branch.class);
		if (from != null) {
			criteria.add(Expression.ge("date",from));
		}
		if (to != null) {
			criteria.add(Expression.le("date",to));
		}
		
		return criteria.list();
	}

	@Override
	public int getNoOfRecords() {
		return ((Number) getSession().createQuery("select count(*) from Branch").uniqueResult()).intValue();
	}


}
